package com.ambitor.grass.sql.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectionUtils {
	
	private static boolean isInited = false;
	
	private static DataSource ds;

	private ConnectionUtils() {
	}

	public static void init(String ContexName) {
		try {
			InitialContext initialContext = new InitialContext();
			ds = (DataSource) initialContext.lookup(ContexName);
			isInited = true;
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection(String ContexName)
			throws SQLException {
		if (!isInited) {
			init(ContexName);
		}
		return ds.getConnection();
	}

	public static Connection getTestConnection(String url, String userName,
			String password) throws SQLException {
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		// url= "jdbc:mysql://127.0.0.1:3306/ipromotion"
		return DriverManager.getConnection(url, userName, password);
	}
}
